package com.LeeCode;

import java.util.HashMap;

/**
 * 必须拿起的最小连续卡牌数
 */

public class Code2260 {
    public static void main(String[] args) {
        int[] cards = {1, 0, 5, 5};
        System.out.println(new Code2260().minimumCardPickup1(cards));
    }

    public int minimumCardPickup(int[] cards) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int ans = Integer.MAX_VALUE;

        for (int i = 0; i < cards.length; i++) {
            if (map.containsKey(cards[i])) {
                ans = Math.min(ans, i - map.get(cards[i]) + 1);
            }
            map.put(cards[i], i);
        }
        return ans == Integer.MAX_VALUE ? -1 : ans;
    }

    public int minimumCardPickup1(int[] cards) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int ans = Integer.MAX_VALUE;

        int left = 0, right;
        for (right = 0; right < cards.length; right++) {
            map.merge(cards[right], 1, Integer::sum);
            while (map.get(cards[right]) == 2) {
                map.merge(cards[left], -1, (old, delta) -> {
                    int res = old + delta;
                    return res == 0 ? null : res;
                });
                ans = Math.min(ans, right - left + 1);
                left++;
            }
        }
        return ans == Integer.MAX_VALUE ? -1 : ans;
    }
}
